//
//  DIYDetailViewController.m
//  BigJoy
//
//  Created by Rowling on 2017/6/16.
//  Copyright © 2017年 Rowling. All rights reserved.
//

#import "DIYDetailViewController.h"
#import "XMbaseCanMoveView.h"
#import "choseTakePhotoVIew.h"
#import "JFImagePickerController.h"
#import "DIYdetailViewModel.h"
#import "TextFieldCanMoceView.h"
#import <IQKeyboardManager.h>
#import "AddView.h"
#import "PreviewVC.h"

@interface DIYDetailViewController ()<UIGestureRecognizerDelegate,XMbaseCanMoveViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong) UIImageView * backGroundImageView;
@property (nonatomic,strong) UIView *backContentView;
@property (nonatomic,strong) UIView *firstView;
@property (nonatomic,strong) UIView *secondView;
@property (nonatomic,strong) UIButton *addButton;
// 当前选中的elementView
@property (nonatomic,strong) UIView *currentView;
// 当前具体哪一面的view
@property (nonatomic,strong) UIView *currentLayerView;
// 覆盖的view
@property (nonatomic,strong) UIImageView *maskView;
@property (nonatomic,strong) UIView *optionViewFirst;
@property (nonatomic,strong) UIView *optionViewSecond;
@property (nonatomic,assign) CGRect optionRect;
// ViewModel
@property (nonatomic,strong) DIYdetailViewModel *viewModel;
@property (nonatomic,strong) UIButton *editingButton;//编辑的button
@property (nonatomic,strong) UIPanGestureRecognizer *pan;
@property (nonatomic,strong) UIRotationGestureRecognizer *rotation;
@property (nonatomic,strong) UIPinchGestureRecognizer *pinch;
@property (nonatomic,assign) BOOL textInput;
// 完成按钮
@property (nonatomic,strong) UIButton *completeButton;
@property (nonatomic,strong) choseTakePhotoVIew * chosePhotoView; // 选择照片的view
@end
@implementation DIYDetailViewController

-(choseTakePhotoVIew *)chosePhotoView {
    if (_chosePhotoView == nil) {
        _chosePhotoView = [[choseTakePhotoVIew alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) titleArray:@[@"拍照",@"从相册选择",@"取消"]];
        @weakify(self);
        [_chosePhotoView.subject subscribeNext:^(id  _Nullable x) {
            @strongify(self);
            NSNumber * number = x;
            NSInteger  interger = [number integerValue];
            if (interger == 0) {
                // 拍照
                [self.viewModel openCamera];
            }
            if (interger == 1) {
                //从相册选择
                [self.viewModel openPhotoFile];
            }
            if (interger == 2) {
                //取消
            }
        }];
    }
    return _chosePhotoView;
}

-(UIView *)optionViewFirst {
    if (_optionViewFirst == nil) {
        _optionViewFirst = [[UIView alloc]init];
    }
    return _optionViewFirst;
}

-(UIView *)optionViewSecond {
    if (_optionViewSecond == nil) {
        _optionViewSecond = [[UIView alloc]init];
    }
    return _optionViewSecond;
}

-(UIImageView *)backGroundImageView {
    if (_backGroundImageView == nil) {
        _backGroundImageView = [[UIImageView alloc]init];
    }
    return _backGroundImageView;
}

-(UIView *)backContentView {
    if (_backContentView == nil) {
        _backContentView = [[UIView alloc]init];
    }
    return _backContentView;
}

-(UIView *)firstView {
    if (_firstView == nil) {
        _firstView = [[UIView alloc]init];
    }
    return _firstView;
}

-(UIView *)secondView {
    if (_secondView == nil) {
        _secondView = [[UIView alloc]init];
    }
    return _secondView;
}

-(DIYdetailViewModel *)viewModel {
    if (_viewModel == nil) {
        _viewModel = [[DIYdetailViewModel alloc] init];
        [_viewModel bindVC:self.view];
        @weakify(self);
        [_viewModel.subject subscribeNext:^(id  _Nullable x) {
            @strongify(self);
            [self addelementwithPhoto:x];
        }];
    }
    return _viewModel;
}

-(UIButton *)completeButton {
    if (_completeButton == nil) {
        _completeButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    }
    [_completeButton setImage:[UIImage imageNamed:@"dui_hong"] forState:UIControlStateNormal];
    return _completeButton;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.optionRect =  CGRectMake ((SCREEN_WIDTH - XMW(300)) / 2, (SCREEN_HEIGHT - XMH(500)) / 2, XMW(300), XMH(500));
    [self setFirstLayer];
    [self setUI];
    [self addAllGesture]; // 添加所有手势
    self.currentLayerView = self.optionViewFirst;
    [self initMaskView];
    [self.viewModel addToolView];// 加入编辑的工具栏view
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

-(void)initMaskView {
    UIImageView *tempView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    tempView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.8];
    CAShapeLayer *layer = [self createMaskLayerWithView:tempView];
    tempView.layer.mask = layer;
    self.maskView = tempView;
    self.maskView.hidden = YES;
    [self.backContentView addSubview:tempView];
}

-(void)setUI {
    // nav
    [self BackClearView];
    UIButton * btn = [XMSuperHelper XMbuttonWithFrame:CGRectMake(0, 0, 50, 50) Tile:@"翻" FontSize:11 selector:@selector(fanBtnClick:) Target:self];
    btn.titleEdgeInsets = UIEdgeInsetsMake(1, 0, 0, 3);
    [btn setTitle:@"正" forState:UIControlStateNormal];
    [btn setTitle:@"反" forState:UIControlStateSelected];
    btn.titleLabel.font = [UIFont systemFontOfSize:11];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"qiehuan"] forState:UIControlStateNormal];
    [self.BackClearView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.BackClearView);
        make.right.equalTo(self.BackClearView);
    }];
    self.view.layer.masksToBounds = YES;
    // addButton
    self.addButton = [XMSuperHelper XMbuttonWithFrame:CGRectMake(SCREEN_WIDTH - 50, SCREEN_HEIGHT - 130, 50, 50) Tile:@"" FontSize:15 selector:@selector(addButtonClick) Target:self];
//    self.addButton.frame = CGRectMake(SCREEN_WIDTH - 70, SCREEN_HEIGHT - 100, 50, 50);
    [self.addButton setImage:[UIImage imageNamed:@"jiahao_youquan"] forState:UIControlStateNormal];
    [self.view addSubview:self.addButton];
    [self.view addSubview:self.completeButton];
    [self.completeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.addButton);
        make.top.equalTo(self.addButton.mas_bottom).offset(10);
        make.height.width.equalTo(@38);
    }];
    self.completeButton.hidden = YES;
    // 点击完成
    @weakify(self);
    [[self.completeButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self okButtonClick];
    }];
}
// 视图第一层
-(void)setFirstLayer {
    self.backContentView.frame = self.view.bounds;
    self.backContentView.y = 20;
    self.backContentView.height -= 20;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backContentView];
    [self setSecondLayerOnBackContentView];
    [self setThirdLayerOnFistrView];
    [self setThirdLayerOnSeondView];
}
// 视图第二层
-(void)setSecondLayerOnBackContentView {
    //secondView
    self.secondView.frame = self.backContentView.bounds;
    [self.backContentView addSubview:self.secondView];
    //firstView
    self.firstView.frame = self.backContentView.bounds;
    [self.backContentView addSubview:self.firstView];
}
// 视图第三层firstView
-(void)setThirdLayerOnFistrView {
    // backimageView
    self.backGroundImageView.frame = self.backContentView.bounds;
    self.backGroundImageView.image = [UIImage imageNamed:@"tim.jpeg"];
    [self.firstView addSubview:self.backGroundImageView];
    self.optionViewFirst.frame = self.optionRect;
    [self.firstView addSubview:self.optionViewFirst];
    self.optionViewFirst.layer.masksToBounds = YES;
}
//视图第三层secondView
-(void)setThirdLayerOnSeondView {
    UIImageView * image = [[UIImageView alloc]init];
    image.image = [UIImage imageNamed:@"tim2.jpg"];
    image.frame = self.backContentView.bounds;
    [self.secondView addSubview:image];
    self.optionViewSecond.frame = self.optionRect;
    [self.secondView addSubview:self.optionViewSecond];
    self.optionViewSecond.layer.masksToBounds = YES;
}
#pragma -mark:翻转按钮Click
-(void)fanBtnClick:(UIButton *)sender {
    if ([self.currentLayerView isEqual:self.optionViewSecond]) {
        sender.selected = NO;
        [self animationWithView:self.backContentView WithAnimationTransition:UIViewAnimationTransitionFlipFromLeft];
        [self.backContentView insertSubview:self.firstView belowSubview:self.maskView];
        self.currentLayerView = self.optionViewFirst;
    }else {
        sender.selected = YES;
        [self animationWithView:self.backContentView WithAnimationTransition:UIViewAnimationTransitionFlipFromRight];
        [self.backContentView insertSubview:self.secondView belowSubview:self.maskView];
        self.currentLayerView = self.optionViewSecond;
    }
}
#pragma -mark:添加按钮点击
-(void)addButtonClick {
    AddView * addView = [[AddView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [addView animationAddToView:XMKEYWINDOWXM];
    @weakify(self);
    [addView setButtonClickBlock:^(NSInteger tag){
        @strongify(self);
        switch (tag) {
            case 0:
            {
                // 照片
                [self showChosePhotoView];
            }
                break;
            case 1:
            {
                //插画
            }
                break;
            case 2:
            {
                //文字
                [self addTextFildCanMoveView];
            }
                break;
            case 3:
            {
                //素材
            }
                break;
                
            default:
                break;
        }
    }];
}
// 添加元素
-(void)addelement {
        XMbaseCanMoveView * elementView = [[XMbaseCanMoveView alloc]init];
        elementView.frame = CGRectMake(0, 0, 200, 200);
        elementView.backgroundColor = [UIColor clearColor];
        elementView.center = self.firstView.center;
        [self.currentLayerView addSubview:elementView];
        self.currentView = elementView;
        elementView.Delegate = self;
    [self.viewModel.elementArray addObject:elementView];
    [self showCompleteButton];
}

// 添加照片元素
-(void)addelementwithPhoto:(UIImage *)image {
    XMbaseCanMoveView * elementView = [[XMbaseCanMoveView alloc]init];
    elementView.image = image;
    CGFloat width = 150;
    CGFloat height = (image.size.height / image.size.width) * width;
    elementView.frame = CGRectMake(0, 0, XMW(width), XMH(height));
    elementView.center = self.firstView.center;
    elementView.backgroundColor = [UIColor clearColor];
    [self.currentLayerView addSubview:elementView];
    self.currentView = elementView;
    elementView.Delegate = self;
    [self.viewModel.elementArray addObject:elementView];
    [self showCompleteButton];
}
// 加入文字元素的方法
-(void)addTextFildCanMoveView {
    TextFieldCanMoceView * elementView = [[TextFieldCanMoceView alloc]initWithFrame:CGRectMake(0, 0, XMW(150), XMW(150))];
//    elementView.frame = );
    elementView.centerX = self.optionRect.size.width / 2 ;
    elementView.backgroundColor = [UIColor clearColor];
    [self.currentLayerView addSubview:elementView];
    self.currentView = elementView;
    self.viewModel.cureentView = elementView;
    elementView.Delegate = self;
    elementView.isEditing = YES;
    [self addEditButton:elementView];
    [self.viewModel.elementEditArray addObject:elementView];
    self.textInput = YES;
    [self showCompleteButton];
}

//出现选择照片提示view
-(void)showChosePhotoView {
    [self.view addSubview:self.chosePhotoView];
    [self.chosePhotoView doAnimation];
}

#pragma UIView实现动画
- (void) animationWithView : (UIView *)view WithAnimationTransition : (UIViewAnimationTransition) transition
{
    [UIView animateWithDuration:0.5 animations:^{
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        [UIView setAnimationTransition:transition forView:view cache:YES];
    }];
}
#pragma -mark:各种添加手势的方法
-(void)addAllGesture {
    [self addRotationWithView:self.backContentView];
    [self addPinchWithView:self.backContentView];
    [self addPanWithView:self.backContentView];
}

-(void)addRotationWithView:(UIView *)view {
    UIRotationGestureRecognizer * raotion = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotation:)];
    self.rotation = raotion;
    raotion.delegate = self;
    [self.view addGestureRecognizer:raotion];
}

-(void)addPinchWithView:(UIView *)view {
    UIPinchGestureRecognizer * pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
    self.pinch = pinch;
    pinch.delegate = self;
    [self.view addGestureRecognizer:pinch];
}

-(void)addPanWithView:(UIView *)view {
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panMove:)];
    self.pan = pan;
    [self.view addGestureRecognizer:pan];
}

-(void)rotation:(UIRotationGestureRecognizer *)rotation {
    self.currentView.transform = CGAffineTransformRotate(self.currentView.transform, rotation.rotation);
    [rotation setRotation:0];
}

-(void)pinch:(UIPinchGestureRecognizer *)pinch {
    self.currentView.transform = CGAffineTransformScale(self.currentView.transform, pinch.scale, pinch.scale);
    //    [self addPanWithView:self.canmoView];
    [pinch setScale:1];
}

-(void)panMove:(UIPanGestureRecognizer *)pan {
    self.optionViewFirst.layer.masksToBounds = NO;
    self.optionViewSecond.layer.masksToBounds = NO;
    self.maskView.hidden = NO;
    CGPoint  point = [pan translationInView:self.view];
    self.currentView.center = CGPointMake(point.x + self.currentView.center.x, point.y + self.currentView.center.y);
    [pan setTranslation:CGPointZero inView:self.view];
    if (pan.state == UIGestureRecognizerStateEnded) {
        self.optionViewFirst.layer.masksToBounds = YES;
        self.optionViewSecond.layer.masksToBounds = YES;
        self.maskView.hidden = YES;
    }
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

#pragma -mark:xmCanMoveViewDelegate
-(void)XMbaseCanMoveViewTap:(UIView *)View {
    XMbaseCanMoveView * moveView = (XMbaseCanMoveView *)View;
    self.currentView = moveView;
    [self.currentLayerView addSubview:moveView];
}

-(void)XMbaseCanMoveViewDeleButtonClick:(XMbaseCanMoveView *)View {
    if ([View isKindOfClass:[TextFieldCanMoceView class]]) {
        NSLog(@"dd");
        if (self.textInput) {
            [self remoEditButton];
        }
    }
    self.currentView = nil;
    [self.viewModel remoMoveView:View];
    [self showCompleteButton];
}
// 双击回调
-(void)XMdoublClick:(XMbaseCanMoveView *)View {
    TextFieldCanMoceView * textView = (TextFieldCanMoceView *)View;
    if (self.textInput == YES && [self.currentView isEqual:View]) {
        return;
    }
    self.currentView = textView;
    self.viewModel.cureentView = textView;
    textView.isEditing = YES;
    [self addEditButton:textView];
    self.textInput = YES;
}

//setCurrentView
-(void)setCurrentView:(UIView *)currentView {
    XMbaseCanMoveView * moveViewBefore = (XMbaseCanMoveView *)_currentView;
    moveViewBefore.isSelect = NO;
    _currentView = currentView;
    if (currentView) {
        XMbaseCanMoveView * moveViewAfter = (XMbaseCanMoveView *)currentView;
        moveViewAfter.isSelect = YES;
    }
}
// 传进去一个UIView进行绘制，返回一个 CAShapeLayer 对象，然后把改对象设置为view.layer.mask属性。

- (CAShapeLayer *)createMaskLayerWithView:(UIView *)view{
    //根据自己描绘的路径，绘制想要的形状。
    UIBezierPath *path = [[UIBezierPath bezierPathWithRoundedRect:self.optionRect cornerRadius:0] bezierPathByReversingPath];
    CAShapeLayer *layer = [CAShapeLayer layer];
    UIBezierPath *outPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [outPath appendPath:path];
    layer.path = outPath.CGPath;
    return layer;
}
#pragma -mark:完成按钮click
-(void)okButtonClick {
    self.currentView = nil;
     UIImage * tempImage = [XMSuperHelper imageWithCaputureView:self.secondView];
     UIImage * diyImage = [XMSuperHelper clipWithImageRect:self.optionRect clipImage:tempImage];
    UIImage * tempImage1 = [XMSuperHelper imageWithCaputureView:self.firstView];
    UIImage * diyImage1 = [XMSuperHelper clipWithImageRect:self.optionRect clipImage:tempImage1];
//    UIImageView * imageView = [[UIImageView alloc]init];
//    imageView.image = diyImage;
//    imageView.frame = CGRectMake(0, 0, self.optionRect.size.width, self.optionRect.size.height);
//    [self.view addSubview:imageView];
    NSArray * imgArray = @[diyImage,tempImage,tempImage1,diyImage1];
    PreviewVC * vc = [PreviewVC new];
    vc.imgArray = imgArray;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma -mark:进入编辑状态
-(void)addEditButton:(TextFieldCanMoceView *)moveView {
    UIButton * editButton = [[UIButton alloc]init];
    [XMKEYWINDOWXM addSubview:editButton];
    [editButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(XMKEYWINDOWXM).offset(10);
        make.right.equalTo(XMKEYWINDOWXM).offset(-10);
        make.width.height.equalTo(@50);
    }];
    if (self.editingButton) {
        [self.editingButton removeFromSuperview];
    }
    self.editingButton = editButton;
    [editButton setImage:[UIImage imageNamed:@"dui_bai_youyinying"] forState:UIControlStateNormal];
    @weakify(self);
    [[editButton rac_signalForControlEvents:UIControlEventTouchUpInside ] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self remoEditButton];
    }];
    [self enableAllGesture:NO];
    moveView.tap.enabled = YES;
    moveView.doubleTap.enabled = YES;
    self.BackClearView.hidden = YES;
}

-(void)enableAllGesture:(BOOL)enable {
    self.rotation.enabled = enable;
    self.pan.enabled = enable;
    self.pinch.enabled = enable;
    [self.viewModel editingEnabelTextViewTapCurrentTextView:enable];
}

//退出编辑状态
-(void)remoEditButton {
    if ([self.currentView isKindOfClass:[TextFieldCanMoceView class]]) {
        TextFieldCanMoceView * canMoveView = (TextFieldCanMoceView *)self.currentView;
        canMoveView.isEditing = NO;
        [self.viewModel endEidting];
    }
    self.textInput = NO;
    [self.editingButton removeFromSuperview];
    [self enableAllGesture:YES];
    self.BackClearView.hidden = NO;
}

// 判断是否显示完成按钮
-(void)showCompleteButton {
    if (self.viewModel.elementArray.count == 0 && self.viewModel.elementEditArray.count == 0) {
        self.completeButton.hidden = YES;
    }else {
        self.completeButton.hidden = NO;
    }
}

-(void)dealloc {
    NSLog(@"DIYVC dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self.viewModel];
}

@end
